
// var myRedis = require('./myRedis').config('6379', '127.0.0.1');
var myAxios =  require('./myAxios');

var fs          =  require('fs');
var config      =  require('config');
var parCfg      =  config.get('partnerConfig');
var NodeRSA     =  require('node-rsa');
var express     =  require('express');
var querystring =  require('querystring');
// var nodeDB      =  require('./db');
var md5         =  require('md5');
var url         =  require('url');
var request     =  require('request');
var myCrypto    =  require('crypto');
var myDB        = require('./myDB');

var BS = {
    jsonPost:async function (serUrl, params){
        let result = await myAxios.post(serUrl,params,{headers: {'Content-Type': 'application/json'}});
        return result.data;
    },
    getQuest:async function (serUrl, params){
        return await myAxios.get(serUrl,params)
    },
    randomString:function  (size){
        if(!size){size=32;}
        var a = "-_0987654321asdfghjklzxcvbnmqwertyuiopASDFGHJKLZXCVBNMQWERTYUIOP";
        var len = a.length;
        var result = '';
        for(var i=0; i<size; i++) {
            result += a[0+Math.round(Math.random()*len)];
        }
        return result;
    },
    urlBase64Encode:function (str) {
        let buf = new Buffer(str);
        let base64str = buf.toString('base64');
        base64str = base64str.replace(/\+/g,'-');
        base64str = base64str.replace(/\//g,'_');
        base64str = base64str.replace(/=/g,'');
        console.log(base64str);
        return base64str;
    },
    urlBase64Decode:function (base64str) {
        base64str = base64str.replace(/-/g,'+');
        base64str = base64str.replace(/_/g,'/');
        let mod4 = base64str.length % 4;
        if(mod4){
            base64str += '===='.substr(mod4);
        }
        let buf = new Buffer(base64str,'base64');
        let str = buf.toString('utf8');
        return str;
    },
    decodeName:function (str){},
    encodeName:function (str){},
    decodePass:function (str,userSid){},
    encodePass:function (str,userSid){},
    myRsaEncrypt:function (str, publicKeyFileName){
        let rsaEncodeData = "";
        try {

            let rsaPublicFile  = __projectDir+'/ca/'+publicKeyFileName;
            let rsaPublicKeyStr = fs.readFileSync(rsaPublicFile).toString('ascii');

            let rsaResource = new NodeRSA(rsaPublicKeyStr);
            rsaEncodeData = rsaResource.encrypt(str,'base64',rsaResource);
            rsaEncodeData = urlBase64Encode(rsaEncodeData);
        }catch(err) {
            console.log('rsa加密: '+err);
        }
        return rsaEncodeData;
    },
    myRsaDecrypt:function (rsaEncodeData, privateKeyFileName){
        var rsaDecodeData = "";

        try {
            rsaEncodeData = urlBase64Decode(rsaEncodeData);

            let rsaPrivateFile  = __projectDir+'/ca/'+privateKeyFileName;
            let rsaPrivateKeyStr = fs.readFileSync(rsaPrivateFile).toString('ascii');
            let rsaResource = new NodeRSA(rsaPrivateKeyStr);
            rsaDecodeData = rsaResource.decrypt(rsaEncodeData,'utf8');
        }catch(err){
            console.log('rsa解密: '+err);
        }
        return rsaDecodeData;
    },
    _myRsaEncrypt:function (str, rsaPublicKeyStr){
        str = urlBase64Encode(str);
        var rsaEncodeData = "";
        try {
            var publickey = new NodeRSA(rsaPublicKeyStr);
            rsaEncodeData = publickey.encrypt(str,'base64');
        }catch(err) {
            console.log('rsa加密: '+err);
        }
        return rsaEncodeData;
    },
    _myRsaDecrypt:function (rsaEncodeData, rsaPrivateKeyStr){
        //rsaPrivateKeyStr = rsaPrivateKeyStr.replace(/\n/g,'');
        //rsaPrivateKeyStr = rsaPrivateKeyStr.replace(/\r/g,'');
        let privateKey = {
            "key":rsaPrivateKeyStr,
            "passphrase":"",
            "padding":myCrypto.constants.RSA_NO_PADDING
        }
        // rsaEncodeData = base64Decode(rsaEncodeData);
        var rsaDecodeData = "";
        try {
            // let privatekey = new NodeRSA(rsaPrivateKeyStr);
            // rsaDecodeData = privatekey.decrypt(rsaEncodeData,'utf8');

            let buf = new Buffer(rsaEncodeData);
            let step = 64;
            let box = new Array();
            let x = 0;
            for(var i=0; i<buf.length; i+=step){
                box[x] = myCrypto.privateDecrypt(privateKey,new Buffer(rsaEncodeData.substr(i,step)));
                ++x;
            }
            rsaDecodeData = box.join('');

            //rsaDecodeData = myCrypto.privateDecrypt(privateKey,new Buffer(rsaEncodeData));
        }catch(err){
            console.log('rsa解密: '+err);
        }
        return rsaDecodeData;
    },
    getParams:function (req, key, def){
        var params = "";
        if(typeof req.body[key]!='undefined'){
            params = req.body[key];
        }else if(typeof url.parse(req.url, true).query[key]!='undefined'){
            params = url.parse(req.url, true).query[key];
        }
        if(!params){
            params = def;
        }
        return params;
    },
    getValue:function (data, key, def){
        let res;
        if(typeof def!='undefined'){
            res = def;
        }
        if(typeof data!='undefined' && typeof data[key]!='undefined'){
            res = data[key];
        }

        return res;
    },
    createSign:function (params,appSecret,version){
        var keys = new Array();
        var i = 0;

        for(x in params){
            if(params[x]){
                keys[i] = x;
                ++i;
            }
        }
        keys.sort();
        // console.log(keys);
        var sp = '';
        var stringA = '';
        var value;
        for (var x=0; x<keys.length; x++){
            if(keys[x]=='sign' || keys[x]=='signType'){
                continue;
            }
            value = params[keys[x]];

            if(value){
                stringA += sp + keys[x] + '=' + value;
                sp = '&';
            }
        }
        //差异appSecret  &  appsecret
        let appSecretKey;
        if(!version){
            //爬虫端
            appSecretKey = 'appSecret';
        }else{
            //原来服务端
            appSecretKey = 'appsecret';
        }
        stringA += sp + appSecretKey+'=' + appSecret;
        var md5StringA = md5(stringA);
        return md5StringA.toUpperCase();
    },
    notify:async function (url,params){

        //是否加密通知
        //判断依据是否有合作方预留的公钥
        // if(this.parCfg.partnerPublicKey){
        //     if(typeof params=='object'){
        //         params = JSON.stringify(params);
        //     }
        //     let rsaPublicFileName  = __projectDir+'/ca/'+this.parCfg.partnerPublicKey;
        //     let rsaPublicKeyStr = fs.readFileSync(rsaPublicFileName).toString('ascii');
        //     params = myRsaEncrypt(params,rsaPublicKeyStr);
        //
        //     params = JSON.parse(params);
        // }

        let result = await myAxios.post(url,params,{headers: {'Content-Type': 'application/json'}});
        if(result){
            if(result.data){
                let data = result.data;
                //console.log('【wld/notify】'+JSON.stringify(data));
                return data;
            }else{
                console.error('【wld/notify】缺少 data'+JSON.stringify(result));
            }
        }else{
            console.error('【wld/notify】 发送失败 fail '+JSON.stringify(result));
        }
    },
    paramsSign :function (params){
        let keys = new Array();
        let i = 0;
        for(x in params){
            if(params[x]){
                keys[i] = x;
                ++i;
            }
        }
        keys.sort();
        let sp = '';
        let stringA = '';
        let value;
        for (var x=0; x<keys.length; x++){

            value = params[keys[x]];

            if(value){
                stringA += sp + keys[x] + '=' + value;
                sp = '&';
            }
        }
        let md5StringA = md5(stringA);
        let gjjMD5 =  md5StringA.toUpperCase();
        return gjjMD5
    },
    getLocalInfo: function (familyName,paramsName){
        let interfaces = require('os').networkInterfaces();
        //console.log(interfaces);
        for(var devName in interfaces){

            let iface = interfaces[devName];

            for(var i=0;i<iface.length;i++){
                let alias = iface[i];
                //familyName = 'IPv4'
                if(alias.family === familyName && alias.address !== '127.0.0.1' && alias.address !== '172.27.0.3' && !alias.internal){
                    return alias[paramsName];
                }
            }

        }
    },
    config:async function(cid){
        let Obj = this;
        let localCfg = new Object();
        let DBParCfg = await myDB.getDB("nodeGjjDB").getRowAsync('select * from cfg_partner where cid=?',[cid]);
        for(x in parCfg){

            if(DBParCfg[x]){
                localCfg[x] = DBParCfg[x];
            }else{
                localCfg[x] = parCfg[x];
            }
        }
        Obj.parCfg = localCfg;
        Obj.tokenName = "partner_token_"+cid;
        Obj.lockName  = "token_lock_"+cid;
        return Obj;
    }
}

module.exports = BS;